/**
 * 
 */
package org.vsg.stock.dzh;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.vsg.common.configration.PropertiesSupport;
import org.vsg.stock.basic.StockHelper;
import org.vsg.stock.basic.persistence.StockInfoDao;


/**
 * @author vison
 *
 */
public class StockTicksDataGen {

	private final static Logger logger = LoggerFactory.getLogger(StockTicksDataGen.class);	
	
	static private DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	static private DateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");	
	private File dzh2Txt;

	private String encoding;

	
	public void exec(ApplicationContext appContext , Date fromDate , Date toDate) throws Exception {

		PropertiesSupport proSupport = (PropertiesSupport)appContext.getBean("propertyConfigurer");
		
		String propTickLine = proSupport.getProperties().getProperty("stock.tick.dir");
		if (propTickLine == null) {
			//logger.warn("Property 'propTickLine' is not defined! ");
			throw new Exception("Property 'stock.tick.dir' is not defined!");
		}
		File tickDir = new File(propTickLine);

		String dzh2txtStr = proSupport.getProperties().getProperty("dzh2txt");
		if (dzh2txtStr == null) {
			//logger.warn("Property 'stock.dailyline.dirk' is not defined! ");
			throw new Exception("Property 'dzh2txt' is not defined!");
		}
		dzh2Txt = new File(dzh2txtStr);
		
		encoding = proSupport.getProperties().getProperty("file.encoding");
		
	
		
		Calendar tmpDate = Calendar.getInstance();
		tmpDate.setTime(fromDate);

		StockInfoDao stockInfoDao = (StockInfoDao)appContext.getBean("stockInfoDao");			
		// --- reade the content ---
		List<String> allStkCodes = stockInfoDao.findAllCode();		
		
		StockHelper shelper = StockHelper.getInstance();
		OutputStream os = null;
		
		
		while (toDate.compareTo(tmpDate.getTime()) >= 0) {
			
			Date refDate = tmpDate.getTime();
			tmpDate.add(Calendar.DATE, 1);
			if (!shelper.isTradingDate(refDate)) {
				continue;
			}

			String code = null;
			String dateStr = sdf2.format(refDate);
			String localeDateStr = sdf.format(refDate);
			String prpfile = dateStr+".PRP";
			
			File dateDir = new File(tickDir , localeDateStr);
			if (!dateDir.exists()) {
				dateDir.mkdirs();
			}

			for (Iterator<String> stkCodesIter = allStkCodes.iterator() ; stkCodesIter.hasNext(); ) {
				code = stkCodesIter.next();
				File stkDateFile = new File(dateDir , code+".txt");
				List<String> stkTicks = hqExecCommand(code , prpfile);
				// --- output to file ---
				
				try {
					os = new BufferedOutputStream(new FileOutputStream(stkDateFile));
					
					IOUtils.writeLines(stkTicks,"\n",os);
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					if (os != null) {
						try {
							os.close();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}					
				}
			}
		
		}

		
		// --- zip file ---
		ZipDataToFile zdtf = new ZipDataToFile();
		
		zdtf.zipAndOutputFile(tickDir , tickDir);			
		
	}
	

	private List<String> hqExecCommand(String stockCode , String prpfile) {
		
		Runtime runtime = Runtime.getRuntime();
		
		StringBuffer cmd = new StringBuffer( dzh2Txt.getAbsolutePath() );
		cmd.append(" ");
		cmd.append("getdata ").append("hqmb ");
		cmd.append(stockCode).append(" ");
		cmd.append(prpfile);
		
		List<String> list = new ArrayList();
		InputStream is = null;
		try {
			Process proc = runtime.exec(cmd.toString());
			
			is = proc.getInputStream();
			// using buffer inputstream 
			InputStreamReader reader = new InputStreamReader(is, encoding);
			BufferedReader breader = new BufferedReader(reader);
			String line =breader.readLine();
			 while (line != null) {
			  	// --- parse object---
				line = line.replaceAll("外盘", "buy");
				line = line.replaceAll("内盘", "sell");

				list.add(line);
			    line = breader.readLine();
			  }
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					is = null;
				}
			}
		}

	        
	     return list;
	}	

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Calendar cale = Calendar.getInstance();

		// --- get the from date and to date ---
		Date fromDate = cale.getTime();
		
		Date toDate = cale.getTime();		
		
		for (String arg : args) {
			if (arg.startsWith("-DfromDate=")) {
				String dateString = arg.replaceFirst("-DfromDate=", "").trim();
				try {
					fromDate = sdf.parse( dateString );
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
			if (arg.startsWith("-DtoDate=")) {
				String dateString = arg.replaceFirst("-DtoDate=", "").trim();
				try {
					toDate = sdf.parse( dateString );
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}				
			}
		}
				
		
		ClassLoader clsLoader = StockTicksDataGen.class.getClassLoader();
		// --- run the main page ---
		// build the read the path , dzh's home path
		String[] configContextFiles = {
				"classpath:/configurationContext.xml",
				"classpath*:/applicationContext.xml",
				"classpath*:/dataAccessContext.xml"
		};
		
		ApplicationContext ctx = new ClassPathXmlApplicationContext(configContextFiles,true);
		
	
		StockTicksDataGen mainProg = new StockTicksDataGen();
		
		try {
			mainProg.exec(ctx , fromDate , toDate);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		logger.info("program run ... Ok!");
		



	}

}
